import { User, Token } from 'app/shared/bean';
import { SettingsService } from '@delon/theme';
import { Component, OnDestroy, Inject, Optional } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import {
  SocialOpenType,
  TokenService,
  DA_SERVICE_TOKEN,
} from '@delon/auth';
import { ReuseTabService } from '@delon/abc';
import { environment } from '@env/environment';
import { StartupService } from '@core/startup/startup.service';

import { UserService } from '@shared/user.Service';
import {
  MqttService,
  IMqttMessage,
 } from 'ngx-mqtt';

@Component({
  selector: 'passport-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less'],
})
export class UserLoginComponent implements OnDestroy {
  form: FormGroup;
  error = '';
  type = 0;
  loading = false;

  constructor(
    fb: FormBuilder,
    private router: Router,
    private userService: UserService,
    public msg: NzMessageService,
    private modalSrv: NzModalService,
    private settingsService: SettingsService,
    private _mqttService: MqttService,
    @Optional()
    @Inject(ReuseTabService)
    private reuseTabService: ReuseTabService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: TokenService,
    private startupSrv: StartupService,
  ) {
    this.form = fb.group({
      username: [null, [Validators.required, Validators.minLength(5)]],
      password: [null, Validators.required],
      mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
      captcha: [null, [Validators.required]],
      remember: [true],
    });
    modalSrv.closeAll();
  }

  // region: fields

  get username() {
    return this.form.controls.username;
  }
  get password() {
    return this.form.controls.password;
  }
  get mobile() {
    return this.form.controls.mobile;
  }
  get captcha() {
    return this.form.controls.captcha;
  }

  // endregion

  switch(ret: any) {
    this.type = ret.index;
  }

  // region: get captcha

  // count = 0;
  // interval$: any;

  // getCaptcha() {
  //   this.count = 59;
  //   this.interval$ = setInterval(() => {
  //     this.count -= 1;
  //     if (this.count <= 0) clearInterval(this.interval$);
  //   }, 1000);
  // }

  // endregion

  submit() {
    this.error = '';
    if (this.type === 0) {
      this.username.markAsDirty();
      this.username.updateValueAndValidity();
      this.password.markAsDirty();
      this.password.updateValueAndValidity();
      if (this.username.invalid || this.password.invalid) return;
    } else {
      this.mobile.markAsDirty();
      this.mobile.updateValueAndValidity();
      this.captcha.markAsDirty();
      this.captcha.updateValueAndValidity();
      if (this.mobile.invalid || this.captcha.invalid) return;
    }

    const params = {
        grant_type: 'password',
        username:  this.username.value,
        password: this.password.value,
        scope: 'all',
    };
    this._mqttService.connect({username: this.username.value, password: this.password.value});
    console.log('mqtt connecting...');
    this.userService.postForToken(params).subscribe((res: Token) => {
        // 清空路由复用信息
        // this.reuseTabService.clear();
        res.token = res.access_token;
        res.expires_in = res.expires_in * 1000 + new Date().getTime();
        this.tokenService.set(res);
        this.userService.me().subscribe((user: User) => {
            // 用户信息：包括姓名、头像、邮箱地址
            this.settingsService.setUser(user);
        });
        this.router.navigate(['/']);
    });
      // 清空路由复用信息
      this.reuseTabService.clear();
  }

  // endregion

  ngOnDestroy(): void {
    // if (this.interval$) clearInterval(this.interval$);
  }
}
